import { BaseEditor } from './BaseEditor'
import { CellValue, ValidationResult } from '../types'

export class DateTimeEditor extends BaseEditor {
  protected input: HTMLInputElement | null = null
  
  protected createElement(value: CellValue): HTMLElement {
    const editOptions = this.getEditOptions()
    const type = this.column.editType || 'datetime'
    
    // 创建输入框
    this.input = document.createElement('input')
    
    // 设置输入类型
    switch (type) {
      case 'date':
        this.input.type = 'date'
        break
      case 'time':
        this.input.type = 'time'
        break
      case 'datetime':
      default:
        this.input.type = 'datetime-local'
        break
    }
    
    // 设置属性
    if (editOptions.placeholder) {
      this.input.placeholder = editOptions.placeholder
    }
    
    if (editOptions.required) {
      this.input.required = true
    }
    
    if (editOptions.readonly) {
      this.input.readOnly = true
    }
    
    // 设置日期范围
    if (type === 'date' || type === 'datetime') {
      if (editOptions.minDate) {
        this.input.min = this.formatDateForInput(editOptions.minDate, type)
      }
      if (editOptions.maxDate) {
        this.input.max = this.formatDateForInput(editOptions.maxDate, type)
      }
    }
    
    // 设置初始值
    this.setValue(value)
    
    return this.input
  }
  
  getValue(): CellValue {
    if (!this.input) return null
    
    const value = this.input.value
    if (!value) return null
    
    // 转换为Date对象进行验证
    const date = new Date(value)
    if (isNaN(date.getTime())) return null
    
    // 根据编辑器类型返回不同格式
    const type = this.column.editType || 'datetime'
    
    // 返回MySQL兼容的日期格式，而不是Date对象
    // MySQL日期格式: 'YYYY-MM-DD HH:MM:SS'
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    switch (type) {
      case 'date':
        return `${year}-${month}-${day}`
      case 'time':
        return `${hours}:${minutes}:${seconds}`
      case 'datetime':
      default:
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
  
  setValue(value: CellValue): void {
    if (!this.input) return
    
    if (value instanceof Date) {
      this.input.value = this.formatDateForInput(value, this.column.editType || 'datetime')
    } else if (typeof value === 'string') {
      const date = this.parseDate(value)
      if (date) {
        this.input.value = this.formatDateForInput(date, this.column.editType || 'datetime')
      } else {
        this.input.value = ''
      }
    } else {
      this.input.value = ''
    }
  }
  
  protected customValidate(value: CellValue): ValidationResult {
    if (!(value instanceof Date)) {
      return { valid: true }
    }
    
    const editOptions = this.getEditOptions()
    
    // 验证最小日期
    if (editOptions.minDate) {
      const minDate = editOptions.minDate instanceof Date ? editOptions.minDate : new Date(editOptions.minDate)
      if (value < minDate) {
        return { 
          valid: false, 
          message: `日期不能早于 ${this.formatDate(minDate, 'date')}` 
        }
      }
    }
    
    // 验证最大日期
    if (editOptions.maxDate) {
      const maxDate = editOptions.maxDate instanceof Date ? editOptions.maxDate : new Date(editOptions.maxDate)
      if (value > maxDate) {
        return { 
          valid: false, 
          message: `日期不能晚于 ${this.formatDate(maxDate, 'date')}` 
        }
      }
    }
    
    // 验证禁用日期
    if (editOptions.disabledDates) {
      if (typeof editOptions.disabledDates === 'function') {
        if (editOptions.disabledDates(value)) {
          return { valid: false, message: '该日期不可选' }
        }
      } else if (Array.isArray(editOptions.disabledDates)) {
        const dateStr = this.formatDate(value, 'date')
        const disabled = editOptions.disabledDates.some((d: Date | string) => {
          const disabledStr = this.formatDate(d instanceof Date ? d : new Date(d), 'date')
          return dateStr === disabledStr
        })
        if (disabled) {
          return { valid: false, message: '该日期不可选' }
        }
      }
    }
    
    return { valid: true }
  }
  
  protected applyCustomStyles(): void {
    if (!this.input) return
    
    // 日期时间输入框的特殊样式
    this.input.style.paddingLeft = '8px'
    this.input.style.paddingRight = '8px'
    
    // 移除默认的日期选择器样式（在某些浏览器中）
    this.input.style.webkitAppearance = 'none'
    ;(this.input.style as any).mozAppearance = 'textfield'
  }
  
  protected attachCustomEventListeners(): void {
    if (!this.input) return
    
    // 监听变化事件
    this.input.addEventListener('change', this.handleInput.bind(this))
  }
  
  private formatDateForInput(date: Date | string, type: string): string {
    const d = date instanceof Date ? date : new Date(date)
    if (isNaN(d.getTime())) return ''
    
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    
    switch (type) {
      case 'date':
        return `${year}-${month}-${day}`
      case 'time':
        return `${hours}:${minutes}`
      case 'datetime':
      default:
        return `${year}-${month}-${day}T${hours}:${minutes}`
    }
  }
} 